﻿using System.Text.Json.Serialization;
//using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

namespace wwm.LeetCodeHelper.Servers;

public class GraphQLRequest
{
    private HttpClient _httpClient;

    [JsonPropertyName("OperationName")]
    public string OperationName { get; set; }

    [JsonPropertyName("query")]
    public string Query { get; set; }

    [JsonPropertyName("variables")]
    public Dictionary<string, object> Variables { get; set; }

    public GraphQLRequest(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<GraphQLResponse> PostAsync(string uri)
    {
        var query = new StringContent(
            JsonSerializer.Serialize(this),
            Encoding.UTF8,
            "application/json");
        GraphQLResponse data = null;
        try
        {
            var response = await _httpClient.PostAsync(uri, query);
            var stream = await response.Content.ReadAsStreamAsync();
            data = await JsonSerializer.DeserializeAsync<GraphQLResponse>(stream);
            if (data.Errors != null)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var item in data.Errors)
                {
                    sb.Append($"{item.message}\n");
                }

                throw new ApplicationException(sb.ToString());
            }

        }
        catch (Exception exception)
        {
            //exception.Redirect();
            Console.WriteLine("exception:" + exception.Message);
        }

        return data;
    }



    public class GraphQLResponse
    {
        [JsonPropertyName("data")]
        public Data Data { get; set; }

        [JsonPropertyName("errors")]
        public IList<GQLError> Errors { get; set; }

    }

    public class GQLError
    {
        [JsonPropertyName("message")]
        public string message { get; set; }
    }

    public class Data
    {
        [JsonPropertyName("PatientList")]
        public IList<JsonDocument> PatientList { get; set; }


        [JsonPropertyName("whoAmI")]
        public string WhoAmI { get; set; }

        [JsonPropertyName("PractitionerList")]
        public IList<JsonDocument> PractitionerList { get; set; }

    }


}
